<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'" width="600px">
    <el-form ref="form" :model="form" :inline="true" :rules="rules" size="small" label-width="80px">
      <el-form-item label="任务名称" prop="taskTitle">
        <el-input v-model="form.taskTitle" style="width: 450px;"/>
      </el-form-item>
      <el-form-item label="任务内容" prop="taskContent">
        <el-input v-model="form.taskContent" style="width: 450px;" rows="5" type="textarea"/>
      </el-form-item>
      <el-form-item label="任务地址" prop="taskAddr">
        <el-input v-model="form.taskAddr" style="width: 450px;" rows="3" type="textarea"/>
      </el-form-item>
      <el-form-item label="发起时间">
        <el-date-picker
          v-model="form.inputTime"
          type="datetime"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="联系人" prop="linker">
        <el-input v-model="form.linker"/>
      </el-form-item>
      <el-form-item label="联系电话" prop="cellphone">
        <el-input v-model="form.cellphone"/>
      </el-form-item>
      
      <el-form-item label="要求到场时间" label-width="113px">
        <el-date-picker
            v-model="form.arriveTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="要求完成时间" label-width="113px">
        <el-date-picker
          v-model="form.finishTime"
          type="datetime"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="附件" >
        <el-upload
          :before-remove="handleBeforeRemove"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :on-error="handleError"
          :on-preview="handlePreview"
          :file-list="fileList"
          :headers="headers"
          :action="imagesUploadApi"
          class="upload-demo"
      multiple>
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" style="display: block;" class="el-upload__tip">请勿上传违法文件，且文件不超过15M</div>
    </el-upload>
      </el-form-item>
      <el-form-item label="备注" >
        <el-input v-model="form.notes" style="width: 450px;" rows="5" type="textarea"/>
      </el-form-item>
      <!-- <el-form-item label="录入人" >
        <el-input v-model="form.inputOperator" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="录入时间" >
        <el-input v-model="form.inputTime" style="width: 370px;"/>
      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, edit } from '@/api/tTasks'
import { mapGetters } from 'vuex'
import { del } from '@/api/qiniu'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/index'
export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    sup_this: {
      type: Object,
      default: null
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!this.isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }

    return {
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      dialogImageUrl: '',
      timeDefaultShow: new Date(),
      dialogVisible: false,
      fileList: [],
      files: [],
      loading: false, dialog: false,
      form: {
        id: '',
        taskTitle: '',
        taskContent: '',
        taskAddr: '',
        attachments: '',
        arriveTime: '',
        finishTime: '',
        notes: '',
        linker: '',
        cellphone: '',
        inputOperator: '',
        inputTime: ''
      },
      rules: {
        taskTitle: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        taskContent: [
          { required: true, message: '请输入任务内容', trigger: 'blur' }
        ],
        taskAddr: [
          { required: true, message: '请输入任务地址', trigger: 'blur' }
        ],
        faultDevices: [
          { required: true, message: '请选择报修设备', trigger: 'blur' }
        ],
        linker: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        cellphone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi'
    ])
  },
  methods: {
    isvalidPhone(str) {
      const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      return reg.test(str)
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          
          const fileIds = []
          this.files.forEach(function(data, index) {
            fileIds.push(data.id)
          })
          this.form.attachments = fileIds.join(',')
          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
        }else {
          return false
        }
      });
      
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      this.form.inputTime = parseTime(this.form.inputTime)
      this.form.arriveTime = parseTime(this.form.arriveTime)
      this.form.finishTime = parseTime(this.form.finishTime)
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.form = {
        id: '',
        taskTitle: '',
        taskContent: '',
        attachments: '',
        arriveTime: '',
        finishTime: '',
        notes: '',
        linker: '',
        cellphone: '',
        inputOperator: '',
        inputTime: ''
      }
    },
    handlePreview(file) {
      document.location.href = file.url
    },
    handleSuccess(response, file, fileList) {
      const uid = file.uid
      const id = response.data[0]
      this.files.push({ uid, id })
    },
    handleBeforeRemove(file, fileList) {
      const _this = this
      for (let i = 0; i < this.files.length; i++) {
        if (this.files[i].uid === file.uid) {
          del(this.files[i].id).then(res => { 
            _this.pictures.splice(i,1)
          })
          return true
        }
      }
    },
    handleRemove(file, fileList) {
      this.form.attachments = this.form.attachments.replace(file.name,"")
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 刷新列表数据
    // doSubmit() {
    //   this.fileList = []
    //   this.dialogVisible = false
    //   this.dialogImageUrl = ''
    //   this.dialog = false
    //   this.$parent.$parent.init()
    // },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    }
  }
}
</script>

<style scoped>

</style>
